package ru.averta.notes.web;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import ru.averta.notes.domain.User;
import ru.averta.notes.domain.forms.UserForm;
import ru.averta.notes.exceptions.UserAlreadyExistsException;
import ru.averta.notes.service.UserService;

@Controller
@RequestMapping(value = {"/register", "/notes/register"})
public class UserRegisterController {

    private static final String MA_USER = "user";
    
    @Autowired
    UserService userService;

    @RequestMapping(method = RequestMethod.GET)
    public void display(Model model) {
        model.addAttribute(MA_USER, new UserForm());
    }

    @RequestMapping(method = RequestMethod.POST)
    public String register(HttpServletRequest request, @Valid @ModelAttribute(MA_USER) UserForm user, BindingResult result, Model model) {

        if (result.hasErrors()) {
            return "register";
        }

        try {
            userService.createUser(user.loadToDomainObject(new User()));
        } catch (UserAlreadyExistsException e) {
            result.reject("register.user.already.exists", new Object[]{user}, "Пользователь " + user.getMail() + " уже существует");
            return "register";
        }
        return "redirect:registerConfirm";

    }
}
